package com.edu.edurealtimepublisher.controller;

import com.edu.edurealtimepublisher.bean.TrafficChBean;
import com.edu.edurealtimepublisher.service.TrafficStatisticsService;
import com.edu.edurealtimepublisher.utils.DateFormatUtil;
import com.edu.edurealtimepublisher.vo.BaseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class TrafficStatisticsController {

    @Autowired
    private TrafficStatisticsService trafficStatisticsService;

    @RequestMapping("getTrafficStatistics")
    private Map<String, Object> getTrafficStatistics(@RequestParam(value = "date", defaultValue = "0") Integer date) {

        if (date == 0) {
            date = DateFormatUtil.now();
        }

        List<TrafficChBean> trafficChBeans = trafficStatisticsService.selectChannelTraffic(date);

        List<String> categories = new ArrayList<>();

        List<BigDecimal> uvCountList = new ArrayList<>();
        List<BigDecimal> svCountList = new ArrayList<>();
        List<BigDecimal> sessionAvgPvList = new ArrayList<>();
        List<BigDecimal> sessionAvgDurTimeList = new ArrayList<>();
        List<BigDecimal> jumpRateList = new ArrayList<>();

        trafficChBeans.forEach(trafficChBean -> {
            categories.add(trafficChBean.getChannel());
            uvCountList.add(trafficChBean.getUvCount());
            svCountList.add(trafficChBean.getSvCount());
            sessionAvgPvList.add(trafficChBean.getSessionAvgPv());
            sessionAvgDurTimeList.add(trafficChBean.getSessionAvgDurTime());
            jumpRateList.add(trafficChBean.getJumpRate());
        });


        BaseVo uvCountVo = new BaseVo("独立访客数", uvCountList);
        BaseVo svCountVo = new BaseVo("会话总数", svCountList);
        BaseVo sessionAvgPvVo = new BaseVo("会话平均浏览页面数", sessionAvgPvList);
        BaseVo sessionAvgDurTimeVo = new BaseVo("会话平均停留时长", sessionAvgDurTimeList);
        BaseVo jumpRateVo = new BaseVo("跳出率", jumpRateList);

        List<BaseVo> series = new ArrayList<>();
        series.add(uvCountVo);
        series.add(svCountVo);
        series.add(sessionAvgPvVo);
        series.add(sessionAvgDurTimeVo);
        series.add(jumpRateVo);

        Map<String, Object> data = new HashMap<>();
        data.put("categories", categories);
        data.put("series", series);

        Map<String, Object> result = new HashMap<>();
        result.put("status", 0);
        result.put("data", data);

        return result;

    }

}
